package com.jwthhealth_pub.old.report.view.fragment;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.common.LogUtil;
import com.jwthhealth_pub.old.report.model.resbody.HraDateRes;
import com.jwthhealth_pub.old.report.presenter.ReportContect;
import com.jwthhealth_pub.old.report.presenter.ReportPresenter;
import com.jwthhealth_pub.old.report.view.FoodSuggestActivity;
import com.jwthhealth_pub.old.report.view.NewReportInfoActivity;
import com.jwthhealth_pub.old.report.view.SportSuggestActivity;
import com.jwthhealth_pub.old.report.view.adapter.ReportHomeAdapter;
import com.jwthhealth_pub.old.report.view.widget.Jwth_CircleProgressbar;
import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;

public class ReportContentFragment extends Fragment implements ReportContect.view {

    private static final String TAG = makeLogTag(ReportContentFragment.class);

//    final int[] mColors = new int[] {
//            0xFFFF80AB,
//            0xFFFF4081,
//            0xFFFF5177,
//            0xFFFF7997
//    };

    final int[] mColors = new int[]{
//            0xFFFFAB00,
//            0xFF46a3ff,
            0xffffffff
    };

    float mScoreProgressbar = 0;
    @BindView(R.id.mLayout)
    CardView mLayout;
    @BindView(R.id.btn_diet_suggest)
    Button btnDietSuggest;
    @BindView(R.id.btn_sport_suggest)
    Button btnSportSuggest;

    Unbinder unbinder;

    private ReportPresenter mPresenter;
    //    private CircleProgressbar mCircleProgressbar;
    private Jwth_CircleProgressbar mCircleProgressbar;
    //    private CircleProgressbar mCircleProgressbar;
    RecyclerView physicalRv, environmentRv;
    private TextView name, time;
    private List<HraDateRes.DataBean> mDatelist;
    private boolean isDataShow;

    public boolean isDataShow() {
        return isDataShow;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

//        if (savedInstanceState != null) return null;

        View view = inflater.inflate(R.layout.fragment_content, container, false);

        unbinder = ButterKnife.bind(this, view);

        mCircleProgressbar = view.findViewById(R.id.circle);
        name = view.findViewById(R.id.name);
        time = view.findViewById(R.id.time);
        physicalRv = view.findViewById(R.id.phycisical_rv);
        environmentRv = view.findViewById(R.id.environment_rv);

        View dateLayout = view.findViewById(R.id.date_layout);

//        mLayout.setBackgroundColor(mColors[0]);


        //膳食建议，运动建议
        Drawable dietDrawableTop = getResources().getDrawable(R.mipmap.food_suggest);
        dietDrawableTop.setBounds(0, 0, 60, 60);
        btnDietSuggest.setCompoundDrawables(null, dietDrawableTop, null, null);

        dietDrawableTop = getResources().getDrawable(R.mipmap.sport_suggest);
        dietDrawableTop.setBounds(0, 0, 60, 60);
        btnSportSuggest.setCompoundDrawables(null, dietDrawableTop, null, null);

        dateLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDatelist = mPresenter.getmUserDateList();
                if (mDatelist != null)
                    if (mDatelist.size() > 0) {
                        showUserList(mDatelist);
                    } else {
                        toast(getString(R.string.nodata));
                    }
            }
        });

        return view;
    }

    @Override
    public void setPresenter(ReportContect.presenter presenter) {
        mPresenter = (ReportPresenter) presenter;
    }

    @Override
    public void showContentUI() {
        NewReportInfoActivity activity = (NewReportInfoActivity) getActivity();
        if (activity == null) return;
        activity.showContentFragment();

        mDatelist = mPresenter.getmUserDateList();
        if (mDatelist != null && mDatelist.size() > 0) {
            isDataShow = true;
            HraDateRes.DataBean dataBean = mDatelist.get(0);
            refreshDateUi(dataBean);
        } else {
            isDataShow = false;
            name.setText(getString(R.string.nodata));
        }

        initRv(physicalRv, 0);
        initRv(environmentRv, 1);
    }

    @Override
    public void showUserList(final List<HraDateRes.DataBean> dataBeen) {

        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getActivity());
        bottomSheetDialog.setContentView(R.layout.item_bottom_dialog);

        TextView completeBtn = (TextView) bottomSheetDialog.findViewById(R.id.tv_complete);
        // TODO: 2017/11/8  
        ImageView closeBtn = (ImageView) bottomSheetDialog.findViewById(R.id.btn_close);
        final LoopView loopView = (LoopView) bottomSheetDialog.findViewById(R.id.loopView);

        final ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < dataBeen.size(); i++) {
            HraDateRes.DataBean dataBean = dataBeen.get(i);
            list.add(dataBean.getName() + "    " + dataBean.getRiqi());
        }


        // TODO: 2017/11/8  
        //设置是否循环播放
        if (loopView != null) {
            loopView.setNotLoop();
            //设置原始数据
            loopView.setItems(list);

            //设置初始位置
            loopView.setInitPosition(0);

            //默认选中第一项
            mPresenter.setmDate(dataBeen.get(0));

            //滚动监听
            loopView.setListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(int index) {
                    mPresenter.setmDate(dataBeen.get(index));
                }
            });
        }

        bottomSheetDialog.show();

        if (completeBtn != null)
            completeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HraDateRes.DataBean dateBean = mPresenter.getmDate();
                    mPresenter.loadDate(dateBean);
                    refreshDateUi(dateBean);
                    bottomSheetDialog.dismiss();
                }
            });

        if (closeBtn != null)
            closeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    bottomSheetDialog.dismiss();
                }
            });

    }

    @Override
    public void showCircleProgressbar(final float score) {
//        final float score = 94.1f;
//        final Float progessbar = score / 100 * 360;
//        final Float progessbar = score / 100 * 220;
        if (mCircleProgressbar == null) return;
        final float progressBar = score / 100 * 220;
        mCircleProgressbar.setProgressbar(progressBar, score);

        Observable.interval(30, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
//                .takeWhile(mScoreProgressbar -> mScoreProgressbar < progessbar/2)//下面的回调每加一调用两次，所以这里的值缩小1/2
                .takeWhile(new Predicate<Long>() {
                    @Override
                    public boolean test(@NonNull Long aLong) throws Exception {
                        return mScoreProgressbar < progressBar;
                    }
                })
                .map(new Function<Long, String>() {
                    @Override
                    public String apply(@NonNull Long aLong) throws Exception {
                        //步长
                        mScoreProgressbar = mScoreProgressbar + 1.5f;
                        if (mScoreProgressbar <= progressBar)
                            mCircleProgressbar.setProgressbar(mScoreProgressbar);
                        else
                            mCircleProgressbar.setProgressbar(progressBar);
                        return String.valueOf(mScoreProgressbar);
                    }
                }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull String s) {
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onComplete() {
//                mCircleProgressbar.setProgressbar((int) (score / 100 * 220), score);
                mCircleProgressbar.setProgressbar(progressBar);
            }
        });
    }

    @Override
    public void showCircleProgressbar_develop(float score) {
        float i = score / 100 * 950;
//        startColorChangeAnim();
    }

    private void startColorChangeAnim() {
        ObjectAnimator animator = ObjectAnimator.ofInt(mLayout, "backgroundColor", mColors);
        animator.setDuration(3000);
        animator.setEvaluator(new ArgbEvaluator());
        animator.start();
    }

    @Override
    public void toast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showErrorUi(String msg) {
        NewReportInfoActivity activity = (NewReportInfoActivity) getActivity();
        activity.showTransitionUi(msg);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    /**
     * @param type 0:9, 1:6
     */
    private void initRv(RecyclerView rv, int type) {
        if (rv == null) return;
        GridLayoutManager gl = new GridLayoutManager(getActivity(), 3);
//        rv.setHasFixedSize(true);
        rv.setLayoutManager(gl);
        rv.setAdapter(new ReportHomeAdapter((NewReportInfoActivity) getActivity(), type));
    }

    private void refreshDateUi(HraDateRes.DataBean dataBean) {
        if (dataBean != null && dataBean.getName() != null && dataBean.getRiqi() != null) {
            if (name == null || time == null) return;
            name.setText(dataBean.getName());
            time.setText(dataBean.getRiqi());
        }
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @OnClick({R.id.btn_diet_suggest, R.id.btn_sport_suggest})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_diet_suggest:
                if (mPresenter == null) return;
                HraDateRes.DataBean dataBean = mPresenter.getmDate();

                if (dataBean == null) return;
                String nid = dataBean.getNid();

                if (nid == null) return;

                Intent intent = new Intent(getActivity(), FoodSuggestActivity.class);
                intent.putExtra("id", dataBean.getNid());
                startActivity(intent);
                break;
            case R.id.btn_sport_suggest:
                if (mPresenter == null) return;
                HraDateRes.DataBean _dataBean = mPresenter.getmDate();

                if (_dataBean == null) return;
                String _nid = _dataBean.getNid();

                if (_nid == null) return;

                Log.d(TAG, _nid);
                Intent _intent = new Intent(getActivity(), SportSuggestActivity.class);
                _intent.putExtra("id", _dataBean.getNid());
                startActivity(_intent);
                break;
        }
    }
}
